package cn.wk.org.service.impl;

import cn.wk.basic.service.impl.BaseServiceImpl;
import cn.wk.org.domain.Department;
import cn.wk.org.mapper.DepartmentMapper;
import cn.wk.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService  {

    @Autowired
    private DepartmentMapper mapper;

    @Override
    public List<Department> findParent() {

       /* //通过查询
        Department idByParent = mapper.findIdByParent(department.getId());*/
        //查询所有一级和二级部门
        List<Department> parent = mapper.findParent();
        //新建一个list

        //遍历
        for (Department departments : parent){
            //拿到所有的二级部门
            List<Department> children = departments.getChildren();
            //如果list集合为0，那么说明就没有二级部门了，为了页面展示好看，就赋值null
            if(children.size() == 0){
                departments.setChildren(null);
            }
            //这里说明二级部门下面还有数据，但是不知道有多少数据，就需要进行一个递归，来进行一个查询
            this.traverse(children);    //遍历
        }
        return parent;
    }

    //递归N级部门
    private void traverse(List<Department> departments){
        if(departments.size() != 0){    //要不为0才去查，为0的话直接不查
            for(Department department : departments){
                //通过传进来的数据父id去查询子部门
                List<Department> children = mapper.findByParentId(department.getId());
                //把查询出来的下级所有部门设置到上级部门里去
                department.setChildren(children.size() == 0 ? null : children);
                //把下级所有部门再次进行查询下下级
                this.traverse(children);
            }
        }
    }

}
